package com.pucong.gitee.database.backup.business.service.service;

import com.pucong.gitee.database.backup.business.service.mapper.ServiceFileListCatalogueMapper;
import com.pucong.gitee.database.backup.business.service.mapper.ServiceFileListHistoryMapper;
import com.pucong.gitee.database.backup.business.service.mapper.ServiceFileListMapper;
import com.pucong.gitee.database.backup.business.service.mapper.ServiceFileMapper;
import com.pucong.gitee.database.backup.business.service.util.FileOperationService;
import com.pucong.gitee.database.backup.business.service.util.FileOperationServiceFactory;
import com.pucong.gitee.database.backup.business.service.vo.ServiceFileVo;
import com.pucong.gitee.database.backup.common.entity.service.ServiceFile;
import com.pucong.gitee.database.backup.common.entity.sys.UserJwt;
import com.pucong.gitee.database.backup.configuration.exception.BusinessException;
import com.pucong.gitee.database.backup.utils.UUID;
import com.pucong.gitee.database.backup.utils.UserRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;

@Service
@Slf4j
public class ServiceFileServiceImpl implements ServiceFileService{

    @Autowired
    private ServiceFileMapper serviceFileMapper;

    @Autowired
    private ServiceFileListCatalogueMapper serviceFileListCatalogueMapper;

    @Autowired
    private ServiceFileListMapper serviceFileListMapper;

    @Autowired
    private ServiceFileListHistoryMapper serviceFileListHistoryMapper;

    @Override
    public ServiceFile getFileServerById(String id) {
        ServiceFile serviceFile = serviceFileMapper.selectById(id);
        return serviceFile;
    }

    @Override
    public int insertFileServer(ServiceFile serviceFile) {
        UserJwt loginUser = UserRequest.getLoginUser();
        String uuid = UUID.uuid();
        serviceFile.setUuid(uuid);
        serviceFile.setCreateBy(loginUser.getUuid());
        serviceFile.setCreateTime(new Date());
        serviceFileMapper.insert(serviceFile);
        return 1;
    }

    @Override
    public int updateFileServerById(String id, ServiceFile serviceFile) {
        ServiceFile serviceFileUpdate = new ServiceFile();
        serviceFileUpdate.setUuid(id);
        serviceFileUpdate.setServiceFileName(serviceFile.getServiceFileName());
        serviceFileUpdate.setHost(serviceFile.getHost());
        serviceFileUpdate.setPort(serviceFile.getPort());
        serviceFileUpdate.setGroupName(serviceFile.getGroupName());
        serviceFileUpdate.setUsername(serviceFile.getUsername());
        serviceFileUpdate.setPassword(serviceFile.getPassword());
        serviceFileUpdate.setServiceFileType(serviceFile.getServiceFileType());
        serviceFileMapper.updateById(serviceFileUpdate);
        return 1;
    }

    @Override
    public List<ServiceFileVo> getFileServerCatalogueById(String id, String cataloguePath) {
        ServiceFile serviceFile = serviceFileMapper.selectById(id);
        FileOperationService fileService = FileOperationServiceFactory.getFileService(serviceFile);
        List<ServiceFileVo> fileServerCatalogue = fileService.getFileServerCatalogue(cataloguePath);
        fileService.close();
        return fileServerCatalogue;
    }

    @Override
    public Boolean uploadFile(String uuid, MultipartFile file, String path) {
        // 获取文件名
        String fileNameOld = file.getOriginalFilename();
        if(fileNameOld.lastIndexOf(".") <= 0){
            throw new BusinessException("上传文件后缀错误，请设置后缀再上传:" + fileNameOld);
        }
        // 去掉文件夹名称
        int i = fileNameOld.indexOf("/") + 1;
        if(i > 0){
            fileNameOld = fileNameOld.substring(i);
        }
        // 上传
        ServiceFile serviceFile = serviceFileMapper.selectById(uuid);
        FileOperationService fileService = FileOperationServiceFactory.getFileService(serviceFile);
        boolean b = false;
        try(InputStream inputStream = file.getInputStream()) {
            b = fileService.uploadFile(path, inputStream, path, fileNameOld);
        } catch (IOException e) {
            log.error("上传文件失败",e);
            throw new BusinessException("上传文件失败");
        }finally {
            fileService.close();
        }
        return b;
    }

    @Override
    public Boolean deleteFile(String uuid, String path) {
        ServiceFile serviceFile = serviceFileMapper.selectById(uuid);
        FileOperationService fileService = FileOperationServiceFactory.getFileService(serviceFile);
        boolean b = fileService.deleteFile(path);
        fileService.close();
        return b;
    }

    @Override
    public void downLoadFileByPath(String uuid,  String path, HttpServletResponse response) {
        ServiceFile serviceFile = serviceFileMapper.selectById(uuid);
        FileOperationService fileService = FileOperationServiceFactory.getFileService(serviceFile);
        try (final ServletOutputStream outputStream = response.getOutputStream()){
            fileService.downloadFile(outputStream,path);
        } catch (IOException e) {
            log.error("下载文件失败",e);
            throw new BusinessException("下载文件失败");
        }
    }

    @Override
    public void lookFileByPath(String uuid, String path, HttpServletResponse response) {
        ServiceFile serviceFile = serviceFileMapper.selectById(uuid);
        FileOperationService fileService = FileOperationServiceFactory.getFileService(serviceFile);
        try (final ServletOutputStream outputStream = response.getOutputStream()){
            fileService.downloadFile(outputStream,path);
        } catch (IOException e) {
            log.error("预览文件失败",e);
            throw new BusinessException("预览文件失败");
        }
    }
}
